package com.buaa.aiguangxi.utils;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;

public class JwtTokenUtil {
    public static final String TOKEN_HEADER="Authorization";
    public static final String TOKEN_PREFIX="Bearer";
    public static final String PRIMARY_KEY="jwtsecret";
    public static final String ISS="huahuaxiaomuzhu";
    private static final int EXPIRATION = 60 * 60 * 24;
    private static final String ROLE_CLAIMS = "role";
    public static String createToken(String username, String role,int userid, boolean isRememberMe) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, role);
        return Jwts.builder()
                //采用HS512算法对JWT进行的签名,PRIMARY_KEY是我们的密钥
                .signWith(SignatureAlgorithm.HS512, PRIMARY_KEY)
                //设置角色名
                .setClaims(map)
                //设置发证人
                .setIssuer(ISS)
                .setSubject(username)
                .setId(String.valueOf(userid))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION*1000))
                .compact();
    }

    public static String getUserName(String token){
        String username;
        try {
            username = getTokenBody(token).getSubject();
        } catch (    Exception e){
            username = null;
        }
        return username;
    }
    public static String getUserId(String token){
        String userid;
        try{
            userid=getTokenBody(token).getId();
        }catch (Exception e){
            userid=null;
        }
        return userid;
    }
    public static String getUserRole(String token){
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }
    public static boolean isExpiration(String token){
        try{
            return getTokenBody(token).getExpiration().before(new Date());
        } catch(ExpiredJwtException e){
            return true;
        }catch (IllegalArgumentException e){
            return false;
        }catch (NullPointerException e){
            return false;
        }
    }
    public static Claims getTokenBody(String token){
        try {
            return Jwts.parser().setSigningKey(PRIMARY_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (MalformedJwtException e){
            return null;
        }
    }
}
